using AngleSharp.Dom;
using Viyi.Strings.Extensions;
using Viyi.Util.Linq;

namespace JamesFan.FetchAreaCodes.Parser;

internal class GeneralContentParser : ContentParser {
    public GeneralContentParser(CodeEntry baseEntry, string content) : base(baseEntry, content) { }

    protected override void ProcessDocument(IDocument document) {
        FindTheTable(document)
            ?.QuerySelectorAll("tr")
            .Skip(1)
            .Select(el => el.QuerySelectorAll("td").ToArray())
            .Where(it => it.Length >= 2)
            .ForEach(pair => AddEntry(
                code: pair[0].TextContent.Trim(),
                name: pair[1].TextContent.Trim(),
                link: pair
                    .Select(el => el.TagName != "A"
                        ? el.QuerySelector("a")?.GetAttribute("href")
                        : el.GetAttribute("href"))
                    .FirstOrDefault(it => !it.IsEmpty())
            ));

        var realLevel = CodeEntry.InferLevel(Entries.Max(it => it.Code.TrimEnd('0').Length));
        if (realLevel > Entries[0].Level) {
            Entries.ForEach(it => it.FixLevel(realLevel));
        }
    }
}
